import React from 'react';
import {Table, Card} from 'antd';
import routes from './routes';
import {Link} from 'react-router-dom';
import PropTypes from 'prop-types';
import {conventEnumValueToString} from '../utils';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {abandonData} from './api';
import {salesLeadSourceType, salesLeadIntentLevel, salesLeadInformationSource, salesLeadStatus, gender} from '../Enum';
import {TABLE, PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, FIXED_COLUMN_WIDTH} from '../constants';

export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }
    abandonConfirm = id => {
        this.setState({
            loading: true
        });
        const record = this.props.data.find(d => d.id === id);
        abandonData(id, record.rowVersion).then(res => {
            this.setState({
                loading: false
            });
            if(res.ok)
                this.props.onChangeSort();
        });
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };

    render() {
        const {pageIndex, pageSize, total} = this.props;
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const columns = [{
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.code',
                defaultMessage: '线索编号'
            }),
            dataIndex: 'code',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
            render: (text, record) => <Link key="detail" to={routes.detail.format(record.id)}>{text}</Link>
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.dealerCode',
                defaultMessage: '总代编号'
            }),
            dataIndex: 'dealerCode',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder,
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.sourceType',
                defaultMessage: '线索来源'
            }),
            dataIndex: 'sourceType',
            render: text => conventEnumValueToString(salesLeadSourceType, text)
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.brandCode',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brandCode',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.customerName',
                defaultMessage: '客户姓名'
            }),
            dataIndex: 'customerName',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.gender',
                defaultMessage: '性别'
            }),
            dataIndex: 'gender',
            render: text => conventEnumValueToString(gender, text)
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.contactNumber',
                defaultMessage: '联系方式'
            }),
            dataIndex: 'contactNumber',
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.intentLevel',
                defaultMessage: '意向级别'
            }),
            dataIndex: 'intentLevel',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'intentLevel' && this.props.sortedOrder,
            render: text => conventEnumValueToString(salesLeadIntentLevel, text)
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.informationSource',
                defaultMessage: '信息来源'
            }),
            dataIndex: 'informationSource',
            render: text => conventEnumValueToString(salesLeadInformationSource, text)
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'status' && this.props.sortedOrder,
            render: text => conventEnumValueToString(salesLeadStatus, text)
        },
        {
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.operate',
                defaultMessage: '操作'
            }),
            dataIndex: 'operate',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [
                    {
                        id: PERMISSION.abandon,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="abandon"
                                placement="topLeft"
                                onConfirm={this.abandonConfirm}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={this.props.intl.formatMessage({
                                    id: 'tablePanel.message.abandon',
                                    defaultMessage: '是否确认作废？'
                                })}>
                                <a>{this.props.intl.formatMessage({
                                    id: 'tablePanel.operation.abandon',
                                    defaultMessage: '作废'
                                })}</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                    },
                ];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        return (
            <Card>
                <Table
                    className={'white-space-nowrap'}
                    columns={columns}
                    dataSource={this.props.data}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    pagination={pagination}
                    rowKey="id"
                    locale={locale}
                    {...TABLE}/>
            </Card>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';
import {injectIntl} from './intl';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));


